<template>
    <div class="cloud-instance">
        <search-table
            :columns="columns"
            :data="instanceList"
            :total="total"
            @change-page="changePageNow"
            @change-size="changePageSize"
            :page.sync="pageIndex"
            :size.sync="pageSize">
        </search-table>
        <Modal
            width="70"
            v-model="show"
            @on-visible-change="visibleChange"
            title="安全组">
            <Select filterable
                class="curret-select"
                v-model="direction"
                @on-change="getSecurityGroups">
                <Option value="ingress">入方向</Option>
                <Option value="egress" >出方向</Option>
            </Select>
            <TableList
                :columns="groupColumnsFilter"
                :hiddenIndex="true"
                :data="groupList"></TableList>
            <div slot="footer" class="footer">
                <Button type="primary" size="large" @click="show = false">确定</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import SearchTable from '@/components/SearchTable/SearchTable'
    import { getInstanceList, getVNC, oppublicServer, resetPublicIp, removeAddress, getSecurityGroups } from '@/api/cloud'

    export default {
        name: 'cloud-instance',
        components: {
            SearchTable
        },
        props: {
            disabledAllBtn: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                show: false,
                direction: 'ingress', // 出入方向搜索条件
                groupColumns: [
                    {
                        title:'授权策略',
                        key:'policy',
                        width: 30,
                        align:'center',
                        render: (h, params) => {
                          return h('span',{
                            style:{
                              color:params.row.policy=='accept'?'green':'red'
                            }
                          },params.row.policy=='accept'?'允许':'拒绝')
                        }
                    },
                    {
                        title:'优先级',
                        key:'priority',
                        width: 50,
                        align:'center',
                    },
                    {
                        title:'协议类型',
                        key:'ipProtocol',
                        width: 50,  
                        align:'center',
                        render: (h, params) => {
                            return h('span',params.row.ipProtocol.toUpperCase())
                        }
                    },
                    {
                        title:'端口范围',
                        key:'portRange',
                        align:'center',
                        width: 90,  
                    },
                    {
                        title:'源地址',
                        key:'sourceCidrIp',
                        align:'center',
                        width:80,  
                    },
                    {
                        title:'目的地址',
                        key:'destCidrIp',
                        align:'center',
                        width:80,  
                    },
                    {
                        title: '描述',
                        key:'description',
                        align:'center',
                        tooltip:true,
                    }
                ],
                groupList: [],
                instanceList: [], // 实例列表
                instanceName: '', // 搜索条件，实例名
                total: 0, // 总数据量
                pageSize: 10, // 分页大小
                pageIndex: 1, // 当前页
                columns: [
                    {
                        placement: 'top-left',
                        title: '名称',
                        key: 'name',
                        align: 'center',
                        tooltip: true,
                        width: 520
                    },
                    {
                        title: 'cpu',
                        key: 'cpu',
                        align: 'center',
                        tooltip: true,
                        width: 26
                    },
                    {
                        title: '内存',
                        key: 'memory',
                        align: 'center',
                        tooltip: true,
                        width: 56
                    },
                    {
                        title: '系统名称',
                        key: 'sysName',
                        align: 'center',
                        tooltip: true,
                        width: 120
                    },
                    {
                        title: '实例计费方式',
                        key: 'instanceChargeType',
                        align: 'center',
                        width: 80,
                        render:(h,params)=>{
                            let txt = ''
                            if(params.row.instanceChargeType =='PostPaid'){
                                txt = '按量付费'
                            }else if(params.row.instanceChargeType =='PrePaid'){
                                txt = '包年包月'
                            }else{
                                txt = '无'
                            }
                            return h('div',txt)
                        }
                    },
                    {
                        title:'内网地址',
                        key:'networkInterfaces',
                        align:'center',
                        width: 170,
                        render:(h,params)=>{
                            let obj = params.row.networkInterfaces[0] || {ipAddress:'',macAddress:''}
                            return h('div',[
                                h('p', {
                                },obj.ipAddress?'IP:'+obj.ipAddress:''),
                                h('p', {
                                },obj.macAddress?'MAC:'+obj.macAddress:''),
                            ])
                        }
                    },
                    {
                        title:'公网地址',
                        key:'elasticIpAddress',
                        align:'center',
                        width: 150,
                        render:(h,params)=>{
                            let obj = params.row.elasticIpAddress || {ipAddress:''}
                            return h('div',{},obj.ipAddress)
                        }
                    },
                    {
                        title:'密码',
                        key:'password',
                        align:'center',
                        width: 100,
                        tooltip: true,
                    },
                    {
                        title: '状态',
                        key: 'status',
                        width: 100,
                        align: 'center',
                        render:(h,params)=>{
                            let st = params.row.status;
                            return h('Tag', {
                                props: {
                                    color: this.filterStatus(st, 'color')
                                }
                            }, this.filterStatus(st, 'text'))
                        }
                    },
                    {
                        title: '地区',
                        key: 'zoneId',
                        width: 100,
                        align: 'center',
                        ellipsis: true,
                        tooltip: true
                    },
                    {
                        title: '描述',
                        key: 'description',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true
                    },
                    {
                        placement: 'top-right',
                        key: 'action',
                        fixed: 'right',
                        align: 'center',
                        render: (h, params) => {
                            let _this = this;
                            let opList = [];
                            let status = params.row.status;
                            let ipObj = params.row.elasticIpAddress || {ipAddress:''}
                            switch (status) {
                                case 'Running':
                                    opList = ['关机','重启','重置公网地址']
                                    break;
                                case 'Stopped':
                                    opList = ['开机','重置公网地址']
                                    break;
                                case 'ChangingEip':
                                    opList = ['不可操作']
                                    break;
                                case 'RemovingEip':
                                    opList = ['不可操作']
                                    break;
                                default:
                                    opList = ['不可操作','重置公网地址']
                                    break;
                            }
                            opList.unshift("操作");
                            if(status!='ChangingEip'&&ipObj.ipAddress&&status!='RemovingEip'){
                                opList.push('移除公网地址')
                            }
                            let operationOption = [];
                            operationOption = opList.map((item, index) => {
                                if (index == 0) {
                                    return h('Option', {
                                    props: {
                                        value: 0,
                                        label: 0
                                    },
                                    class: ['falseValue' + params.row.id],
                                    style: {
                                        display: 'none'
                                    }
                                    }, '')
                                } else {
                                    return h('Option', {
                                    props: {
                                        value: item,
                                        disabled:item == '不可操作' ? true : false
                                    }
                                    }, item)
                                }
                            });
                            return h('div', {
                                    style: {
                                        display: 'flex',
                                        'align-items': 'center'
                                    }
                                }, [
                                    h('div', {
                                    }, [h('Button', {
                                        props: {
                                            type: 'primary'
                                        },
                                        style: {
                                            borderRadius: '4px 0px 0px 4px',
                                            cursor: 'revert'
                                        },
                                    },opList[0]), h('Select', {
                                        class: ['active-select'],
                                        props: {
                                            placeholder: '',
                                            value: 0,
                                            transfer: true
                                        },
                                        style: {
                                            width: '20px'
                                        },
                                        on: {
                                            'on-change': (value) => {
                                                if(value!=0){
                                                if(value == "不可操作") {
                                                    //
                                                } else{
                                                    _this.$Modal.confirm({
                                                        title:"操作云服务器",
                                                        content:"您确定要对这台云服务器"+value+'吗？',
                                                        onOk:()=>{
                                                            _this.handleAliServer(params.row,value)
                                                        },
                                                        onCancel:()=>{

                                                        }
                                                    })
                                                }
                                                }
                                            },
                                        }
                                    }, operationOption)]),
                                    h('Button',{
                                        attrs:{
                                            title:'获取vnc接入界面'
                                        },
                                        style: {
                                            'margin-left': '16px',
                                        },
                                        props: {
                                            placement: 'top',
                                            icon: 'md-desktop',
                                        },
                                        on:{
                                            click: () => {
                                                this.getLoad(params.row.id)
                                            }
                                        }
                                    }),
                                    h('Button',{
                                        attrs:{
                                            title:'查看详情'
                                        },
                                        style: {
                                            'margin-left': '16px',
                                        },
                                        props: {
                                            placement: 'top',
                                            icon: 'ios-search',
                                        },
                                        on:{
                                            click: () => {
                                                this.show = true
                                                this.currentRow = params.row
                                                this.getSecurityGroups()
                                            }
                                        }
                                    })
                                ]
                            )        
                        }
                    }
                ]
            }
        },
        mounted() {
            this.getInstanceList()
        },
        computed: {
            groupColumnsFilter() {
                if(this.direction == 'ingress'){
                    return this.groupColumns.filter(col => col.key !== 'destCidrIp')
                }else{
                    return this.groupColumns.filter(col => col.key !== 'sourceCidrIp')
                }
            }
        },
        methods: {
            visibleChange() {
                this.direction = 'ingress'
            },
            // 打开详情页，获取安全组信息
            getSecurityGroups() {
                let id = this.currentRow.cloudSecurityGroupId
                let regionId = this.currentRow.regionId
                let params = {
                    direction: this.direction,
                    regionId: regionId,
                }
                if(!id){
                  return;
                }
                getSecurityGroups(id,params).then(({ code, data, message })=>{
                    if(code !== 1){
                        this.$message.warning(message)
                        return
                    }
                    this.groupList = data
                }).catch(() => {
                    this.$message.error('获取详情异常')
                })
            },
            // 开、关、重启
            handleAliServer(row,val){
                let status = ''
                if(val == '开机'){
                    status = 'start';
                }else if(val == '关机'){
                    status = 'stop';
                }else{
                    status = 'reboot';
                }
                if(val == '重置公网地址'){
                    resetPublicIp(row.id).then(res=>{
                        if (res.code !== 1) {
                            this.$Message.warning(res.message)
                            return
                        }
                        this.$Message.info(`${val}成功`)
                        this.getInstanceList()
                    }).catch(() => {
                        this.$Message.error(`${val}异常`)
                    })
                }else if(val == '移除公网地址'){
                    removeAddress(row.id).then(res=>{
                        if (res.code !== 1) {
                            this.$Message.warning(res.message)
                            return
                        }
                        this.$Message.info(`${val}成功`)
                        this.getInstanceList()
                    }).catch(() => {
                        this.$Message.error(`${val}异常`)
                    })
                }else{
                    oppublicServer(row.id,status).then(res=>{
                        if (res.code !== 1) {
                            this.$Message.warning(res.message)
                            return
                        }
                        this.$Message.info(`${val}成功`)
                        this.getInstanceList()
                    }).catch(() => {
                        this.$Message.error(`${val}异常`)
                    })
                }
            },
            // 打开vpc接入界面
            getLoad(id){
                getVNC(id,{autoLogin:true}).then(({ code, data, message })=>{
                    if(code === 1){
                        let link = document.createElement('a');
                        link.style.display = 'none';
                        link.href = data;
                        link.target = '_blank'
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                    }else{
                        this.$Message.warning(message)
                    }
                }).catch(()=>{
                    this.$Message.error('连接VPC异常')
                })
            },
            // 转义状态码为中文
            filterStatus(val, type){
                let str = '';
                switch (val) {
                    case 'Pending':
                        str = type === 'text' ? '创建中' : 'orange'
                        break;
                    case 'CreateError':
                        str = type === 'text' ? '创建失败' : 'red'
                        break;
                    case 'Running':
                        str = type === 'text' ? '运行中' : 'green'
                        break;
                    case 'Starting':
                        str = type === 'text' ? '启动中' : 'orange'
                        break;
                    case 'Stopping':
                        str = type === 'text' ? '停止中' : 'orange'
                        break;
                    case 'Stopped':
                        str = type === 'text' ? '已停止' : 'red'
                        break;
                    case 'Rebooting':
                        str = type === 'text' ? '重启中' : 'orange'
                        break;
                    case 'Deleting':
                        str = type === 'text' ? '删除中' : 'orange'
                        break;
                    case 'DeleteError':
                        str = type === 'text' ? '删除失败' : 'red'
                        break;
                    case 'ChangingEip':
                        str = type === 'text' ? '替换公网ip中' : 'orange'
                        break;
                    case 'RemovingEip':
                        str = type === 'text' ? '移除公网地址中' : 'orange'
                        break;
                    default:
                        break;
                }
                return str;
            },
            // 修改当前页
            changePageNow(val) {
                this.pageIndex = val
                this.getInstanceList()
            },
            // 修改分页大小
            changePageSize(val) {
                this.pageSize = val
                this.getInstanceList()
            },
            // 查询实例列表
            getInstanceList() {
                getInstanceList({
                    instanceName: this.instanceName,
                    pageSize: this.pageSize,
                    pageIndex: this.pageIndex,
                    projectId: this.$route.query.prjid
                }).then(({ code, message, data }) => {
                    if (code === 0) {
                        this.$Message.warning(message)
                        return
                    }
                    this.instanceList = data.items || []
                    this.total = data.total || 0
                }).catch(() => {
                    this.instanceList = []
                    this.$Message.error('查询云实例异常')
                }).finally(() => {
                    clearTimeout(this.listTimer)
                    this.listTimer = setTimeout(() => {
                        this.getInstanceList()
                    }, 10000)
                })
            }
        },
        watch: {
        },
        beforeDestroy(){
            clearTimeout(this.listTimer)
        }
    }
</script>

<style scoped>
    .cloud-instance /deep/ .active-select .ivu-select-selection {
        border-radius: 0 4px 4px 0 !important;
    }
    .cloud-instance /deep/ .active-select .ivu-select-selection .ivu-select-selected-value {
        display: none;
    }
    .cloud-instance /deep/ .active-select .ivu-select-selection .ivu-select-arrow {
        margin-right: -6px;
    }
    .curret-select {
        width: 150px;
        margin-bottom: 10px;
    }
</style>